package websocket

import (
	"net/http"
	"sync"

	"github.com/olahol/melody"
)

var (
	myMelody *melody.Melody
	wsOnce   sync.Once
)

// websocket
func CreateWS() *melody.Melody {
	wsOnce.Do(func() {
		myMelody = melody.New()

		// 解决跨域问题
		myMelody.Upgrader.CheckOrigin = func(r *http.Request) bool { return true }

		melodyInit()
	})
	return myMelody
}

// myMelody初始化
func melodyInit() {
	// 客户端连接时
	myMelody.HandleConnect(handleConnect)

	// 客户端断开时
	myMelody.HandleDisconnect(HandleDisconnect)

	// 客户端接收到信息时
	myMelody.HandleMessage(HandleMessage)
}
